import express from "express";
import calcCross from "./calc-cross.js";
import { hi } from "./hifini/puppeteer.js";

const app = express();

/*
  test
  http://localhost:7777/get?token=CCRF2GLCZSK&url=https://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=%E5%91%A8%E6%9D%B0%E4%BC%A6&pn=1&rn=20&httpsStatus=1&reqId=0b923120-1df4-11ee-8718-e7dcba50d115&plat=web_www&from=
  http://localhost:7777/get?token=CCRF2GLCZSK&url=https://m.kuwo.cn/newh5/singles/songinfoandlrc&musicId=169966524
  http://localhost:7777/get?token=CCRF2GLCZSK&url=http://www.kuwo.cn/api/v1/www/music/playUrl&mid=169966524&type=convert_url3&br=128kmp3

*/

const globalStore = {
  hmToken: "",
  Cross: "",
  CrossKey: "Secret",
};

const tokenIsInvalid = (data) => {
  return (
    !data.success &&
    ["token", "illegal"].some((e) => data.message?.toLowerCase()?.includes(e))
  );
};

const refreshCookies = async () => {
  const rs = await fetch("https://www.kuwo.cn/rankList");
  const hmToken = rs.headers.get("Set-Cookie")?.split(";").at(0);
  globalStore.hmToken = hmToken;
  const [key, value] = hmToken?.split("=");
  globalStore.Cross = calcCross(value, key);
};

const getApi = async () => {
  return fetch(
    `https://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=%E5%91%A8%E6%9D%B0%E4%BC%A6&pn=1&rn=20&httpsStatus=1&reqId=0b923120-1df4-11ee-8718-e7dcba50d115&plat=web_www&from=`,
    {
      headers: {
        csrf: "5RD6CR6I8BO",
        cookie: `kw_token=5RD6CR6I8BO; _ga=GA1.2.848284490.1688864236; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1688864236,1688866179,1689298676; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1689298676; _gid=GA1.2.1494217277.1689298676; _gat=1; _ga_ETPBRPM9ML=GS1.2.1689298676.2.0.1689298676.60.0.0;${globalStore.hmToken}`,
        Referer: "https://www.kuwo.cn/",
        [globalStore.CrossKey]: globalStore.Cross,
      },
    }
  ).then((r) => r.json());
};

app.get("/get", async (req, res) => {
  const url = req.query.url;
  const query = { ...req.query };
  const token = query.token;
  delete query.url;
  delete query.token;
  const queryString = new URLSearchParams(Object.entries(query)).toString();
  const r = await fetch(`${url}?${queryString}`, {
    headers: {
      cookie: `kw_token=${token}`,
      Referer: "https://www.kuwo.cn/",
    },
  });
  const data = await r.json();
  res.send(data);
});

app.get("/api", async (req, res) => {
  let data = await getApi();
  if (tokenIsInvalid(data)) {
    await refreshCookies();
    data = await getApi();
  }
  res.send(data);
});

app.get("/search", async (req, res) => {
  const keyword = req.query.keyword;
  const pageNum = req.query.pageNum;
  const data = await hi.search(keyword, pageNum);
  res.send(data);
});

app.get("/song", async (req, res) => {
  const url = req.query.url;
  const song = await hi.getSong(url);
  res.send(song);
});

app.listen(7777, () => {
  console.log("服务启动成功");
});
